package com.pronhub.luowowo.website.web.interceptor;

import com.alibaba.dubbo.config.annotation.Reference;
import com.pronhub.luowowo.member.domain.UserInfo;
import com.pronhub.luowowo.service.IUserInfoRedisService;
import com.pronhub.luowowo.website.web.annotation.RequireLogin;
import com.pronhub.luowowo.website.web.util.CookieUtil;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

public class CheckedLoginInterceptor implements HandlerInterceptor{
    @Reference
    IUserInfoRedisService userInfoRedisService;
    /**
     *  控制检查 是否登录了 还有其他登录的权限检查
     * @param request
     * @param response
     * @param handler
     * @return
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws IOException {
        //对贴了注解的类进行控制
        UserInfo userInfo =null;
        if(handler instanceof HandlerMethod){
            HandlerMethod hm = (HandlerMethod)handler;
            String token = CookieUtil.getToken(request, response);
             userInfo = userInfoRedisService.getUserInfoByToken(token);
            if (hm.hasMethodAnnotation(RequireLogin.class)){
                //如果有就那进行登录验证
                //1得到 token
                //2得到相对的UserInfo
                //3进行判断操作
                //如果没有登录 就返回flase
                if (userInfo == null){
                    response.sendRedirect("/login.html");
                    return false;
                }
            }
        }
        request.getSession().setAttribute("userInfo",userInfo);
        return true;
    }
}
